import getApiData, { getApisData } from '@/services/cpasRequest';

export async function FinancialIndicatorsGet(params: { dbName: string }) {
  try {
    const res = await getApiData('FinancialIndicators.get', params);
    if (res.ok) {
      return Promise.resolve({
        data: res.data,
        success: true,
      });
    }
    return Promise.resolve({
      data: '接口FinancialIndicators.get出错了！',
      success: false,
    });
  } catch (error) {
    return Promise.resolve({
      data: '接口FinancialIndicators.get出错了！',
      success: false,
    });
  }
}

export async function updateFinancialIndicators(dbname: string, paramsData: any[]) {
  const postData = {
    apis: [
      {
        name: 'sqlApi.update',
        params: { name: `[${dbname}]..FinancialIndicators`, rows: paramsData },
      },
    ],
    reload: true,
    params: {},
  };
  const resApis = await getApisData(postData);
  const resUpdate = resApis.data['sqlApi.update'];
  if (resApis.ok && resUpdate.ok) {
    return Promise.resolve({
      data: 'FinancialIndicators, 更改信息成功！',
      success: true,
    });
  }
  return Promise.resolve({
    data: resApis.data,
    success: false,
  });
}

export const mergeArrays = (arr1: any[], arr2: any[]) => {
  // 获取父元素 (p === 0)
  debugger;
  const parents1 = arr1.filter((item) => item.TaskIndicatorID_Parent_ID === '0');
  const parents2 = arr2.filter((item) => item.TaskIndicatorID_Parent_ID === '0');
  // 存储合并结果
  let result = [...arr1];
  // 遍历第二个数组的父元素
  parents2.map((parent2) => {
    // 查找第一个数组中 b 相等的父元素
    const matchingParent1 = parents1.find(
      (parent1) => parent1.IndicatorName === parent2.IndicatorName,
    );
    if (matchingParent1) {
      // 找到匹配的父元素，合并子元素
      const children2 = arr2.filter(
        (item) => item.TaskIndicatorID_Parent_ID === parent2.IndicatorID,
      ); // 获取parent2的子元素
      children2.forEach((child) => {
        child.TaskIndicatorID_Parent_ID = matchingParent1.IndicatorID; // 更新子元素的父引用指向第一个数组的父元素
        let loc = result.findLastIndex(
          (a: any) => a.TaskIndicatorID_Parent_ID === matchingParent1.IndicatorID,
        );
        if (loc > 0) {
          result.splice(loc + 1, 0, child);
        }

        //   result.push(child); // 添加子元素
      });
    } else {
      // 没有匹配的父元素，直接将parent2和其子元素添加到result
      result.push(parent2);
      const children2 = arr2.filter(
        (item) => item.TaskIndicatorID_Parent_ID === parent2.IndicatorID,
      ); // 获取parent2的子元素
      result.push(...children2); // 添加子元素
    }
  });

  return result;
};

const cpCellRegex = /CP_CELL\(".*?","(.*?)",".*?"\)/g;
export const parseFormula = (expression: string) => {
  // 替换 CP_CELL 函数中的第二个参数
  let result = expression.replace(cpCellRegex, (match, cell) => cell);
  debugger;
  // 使用堆栈来处理括号
  let stack = [];
  let currentIndex = 0;
  let output = '';

  while (currentIndex < result.length) {
    let char = result[currentIndex];

    if (char === '(') {
      stack.push(output.length);
      output += char;
    } else if (char === ')') {
      if (stack.length > 0) {
        stack.pop();
        output += char;
      }
    } else {
      output += char;
    }

    currentIndex++;
  }

  // 替换所有 CP_CELL 函数

  output = output.replace(cpCellRegex, (match, cell) => cell);

  return output;
};
